package com.mooc.yohoshop.ui.category;

import androidx.recyclerview.widget.RecyclerView;

import com.mooc.yohoshop.ApiService;
import com.mooc.yohoshop.entity.BaseEntity;
import com.mooc.yohoshop.entity.ErroEntity;
import com.mooc.yohoshop.entity.MenuEntity;
import com.mooc.yohoshop.network.BaseRepository;
import com.mooc.yohoshop.network.HttpFactory;
import com.mooc.yohoshop.network.HttpType;
import java.util.HashMap;
import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

public class CategoryRepo extends BaseRepository {

    public Observable<BaseEntity> requestCategory(HashMap map){
        return convertObservable(HttpFactory.factory(HttpType.SIGNTYPE)
                .getRetrofit().create(ApiService.class)
                .requestCategory(createBody(map)));
    }

    public Observable<BaseEntity> requestMenu(){
        return HttpFactory.factory(HttpType.UPLOADTYPE)
                .getRetrofit().create(ApiService.class).requestMenu()
                .flatMap(new Function<MenuEntity, Observable<BaseEntity>>() {
                    @Override
                    public Observable<BaseEntity> apply(@NonNull MenuEntity menuEntity) throws Exception {
                        if (!menuEntity.status.equals("200")){
                            ErroEntity entity = new ErroEntity();
                            entity.status = "100";
                            entity.message = "菜单获取出错";
                            return Observable.just(entity);
                        }
                        if (menuEntity.data.isEmpty()){
                            ErroEntity entity = new ErroEntity();
                            entity.status = "100";
                            entity.message = "菜单获取出错";
                            return Observable.just(entity);
                        }
                        menuEntity.data.get(0).sel = true;
                        HashMap<String,Object>map = new HashMap<>();
                        map.put("menuId",""+menuEntity.data.get(0).menu_id);
                        return Observable.merge(convertObservable(Observable.just(menuEntity)),
                                convertObservable(HttpFactory.factory(HttpType.SIGNTYPE)
                                        .getRetrofit().create(ApiService.class)
                                        .requestCategory(createBody(map))));
                    }
                });
    }

}
